package com.djl.zenithbite.repository.impl;

import com.djl.zenithbite.entity.User;
import com.djl.zenithbite.entity.UserExample;
import com.djl.zenithbite.repository.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * 用户仓储服务
 */
@Repository
public class UserRepositoryImpl {

    @Autowired
    private UserMapper userMapper;

    /**
     * 通过Username查询User
     * @param username
     * @return
     */
    public User selectByUserName(String username){
        UserExample example = new UserExample();
        UserExample.Criteria criteria = example.createCriteria();
        criteria.andUserNameEqualTo(username);
        List<User> users = userMapper.selectByExampleWithBLOBs(example);
        return Optional.ofNullable(users).orElse(new ArrayList<>()).stream().findFirst().orElse(null);
    }

    /**
     * 通过UserEmail查询User
     * @param userEmail
     * @return
     */
    public User selectByUserEmail(String userEmail){
        UserExample example = new UserExample();
        UserExample.Criteria criteria = example.createCriteria();
        criteria.andUserEmailEqualTo(userEmail);
        List<User> users = userMapper.selectByExample(example);
        return Optional.ofNullable(users).orElse(new ArrayList<>()).stream().findFirst().orElse(null);
    }

    public void addUser(User user){
        userMapper.insertSelective(user);
    }

    public void updateUserPsw(User user) {userMapper.updateByPrimaryKeySelective(user); }
}
